/*
 * 按键初始化及按键扫描
 * K1 GPIOB28 AE25; 按下为低电平
 * K2 GPIOB29 AE24;
 * K3 GPIOB30 AD24;
*/

#include "key.h"

void key_init(){
    GPIOBALTFN1 &= ~((3 << 24) | (3 << 26) | (3 << 28));    // 交替函数功能选择
    GPIOBALTFN1 |= ((1 << 24) | (1 << 26) | (1 << 28));

    GPIOBOUTENB &= ~((1 << 24) | (1 << 26) | (1 << 28));    // 输入模式
}

int get_key_status(int num){
    switch(num){
        case 1:
            return !((GPIOBPAD >> 28) & 1);
        case 2:
            return !((GPIOBPAD >> 29) & 1);
        case 3:
            return !((GPIOBPAD >> 30) & 1);
    }

    return 0;
}

int key_scan(int mode){
    static int key_up = 1;  // 按键状态

    if(mode) key_up = 1;    // 支持长按
    if(key_up && (KEY1 == 1 || KEY2 == 1 || KEY3 == 1)){
        key_up=0;
		if(KEY1 == 1) return 1;
		else if(KEY2 == 1) return 2;
		else if(KEY3 == 1) return 3;
    }else if(KEY1 == 0 && KEY2 == 0 && KEY3 == 0){
        key_up = 1;
    }

    return 0;
}

